// 引入vuex模块
import { createStore } from 'vuex';

// state: 状态（需要在系统中要到的数据）
const state = {
    messages: [
        // {type: "info",message: "测试"},
        // {type: "warning",message: "测试"},
        // {type: "success",message: "测试"},
        // {type: "error",message: "测试"},
    ]
}

let _messageId = 1;

// 同步更新
const mutations = {
    
}

// 状态加工
const getters = {
    
}

// 异步更新
const actions = {
    addMessage(context,payload) {
        let value = payload;
        let messageId = _messageId ++;
        // 弹窗自动关闭时间
        let duration = 3000;
        // 非对象（基本数据类型），转成一个仿照ElementPlus的API对象
        if (typeof payload != 'object') {
            value = {
                message: payload,
                type: 'info',
                messageId
            }
            // 如果是对象，就当作是一个ElementPlus的API对象
        } else {
            value.messageId = messageId;
            duration = payload.duration || 3000;
        }
        console.log("value = ",value);
        context.state.messages.push(value);
        // 显示3秒后自动移除
        setTimeout(() => {
            const index = context.state.messages.findIndex(v => v.messageId == messageId);
            // console.log("删除index = ",index);
            if (index >= 0) {
                context.state.messages.splice(index,1);
            }
        },duration)
    }
}

// 使用创建函数创建vuex对象
export default createStore({  
    state,getters,mutations,actions
});